package com.framework.bdf4j.sysadm.controller;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.framework.bdf4j.annotations.SysLog;
import com.framework.bdf4j.comm.Constants;
import com.framework.bdf4j.comm.util.R;
import com.framework.bdf4j.comm.web.WebUtil;
import com.framework.bdf4j.sysadm.entity.SysDept;
import com.framework.bdf4j.sysadm.entity.SysUser;
import com.framework.bdf4j.sysadm.service.SysDeptService;
import com.framework.bdf4j.sysadm.service.SysUserService;
import com.framework.bdf4j.sysadm.vo.Ztree;

import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;

/**
 * <p>
 * 部门管理 前端控制器
 * </p>
 *
 */
@Controller
@AllArgsConstructor
@RequestMapping("/admin/dept")
@Api(value = "dept", tags = "部门管理模块")
public class SysDeptController {
    private final SysDeptService sysDeptService;
    private final SysUserService userService;

    // 跳转到部门列表页
    @GetMapping("/index")
    public String goDept() {
        return "sysadm/dept/deptList";
    }

    // 跳转到部门编辑页
    @GetMapping("/goEditDept")
    public String goEditDept(@RequestParam(required = false) String id, @RequestParam String oper, Model model) {
        SysDept dept = new SysDept();
        if (!"add".equals(oper)) {
            dept = sysDeptService.getById(Integer.parseInt(id));
            if (0 != dept.getParentId())
                dept.setParentName(sysDeptService.getById(dept.getParentId()).getName());
        }
        model.addAttribute("viewobject", dept);
        model.addAttribute("oper", oper);
        return "sysadm/dept/deptEdit";
    }

    /**
     * 返回树形菜单集合
     *
     * @return 树形菜单
     */
    @ResponseBody
    @GetMapping(value = "/tree")
    public List<Ztree> getTree() {
        return sysDeptService.selectTree();
    }

    /**
     * 选择部门树
     */
    @GetMapping("/selectDeptTree")
    public String selectDeptTree(@RequestParam(required = false) String deptId, ModelMap mmap) {
        SysDept dept = new SysDept();
        if (StringUtils.isNotEmpty(deptId)) {
            dept = sysDeptService.getById(deptId);
        }
        mmap.put("dept", dept);
        return "sysadm/dept/tree";
    }

    /**
     * 分页查询角色信息
     *
     * @param page
     *            分页对象
     * @return 分页对象
     */
    @PostMapping("/list")
    @ResponseBody
    public List<SysDept> getDeptList(SysDept sysdept) {
        if (StringUtils.isEmpty(sysdept.getDeptCode()))
            sysdept.setDeptCode(null);
        if (StringUtils.isEmpty(sysdept.getName()))
            sysdept.setName(null);
        Integer rootId = 0;
        if(WebUtil.getHttpCurrentUserDptId()!=null) {
            sysDeptService.getById(WebUtil.getHttpCurrentUserDptId()).getParentId();
        }
        WebUtil.setHttpSession(Constants.CURRENT_PARENTDEPTID, rootId);
        return sysDeptService.listDept(sysdept);
    }

    /**
     * 分页查询角色信息
     *
     * @param page
     *            分页对象
     * @return 分页对象
     */
    @GetMapping("/page")
    @ResponseBody
    public R getDeptLists(Page page, SysDept sysdept) {
        if (StringUtils.isEmpty(sysdept.getDeptCode()))
            sysdept.setDeptCode(null);
        if (StringUtils.isEmpty(sysdept.getName()))
            sysdept.setName(null);
        Integer rootId = 0;
        if(WebUtil.getHttpCurrentUserDptId()!=null) {
            sysDeptService.getById(WebUtil.getHttpCurrentUserDptId()).getParentId();
        }
        WebUtil.setHttpSession(Constants.CURRENT_PARENTDEPTID, rootId);
        return R.ok(sysDeptService.listDeptPage(page,sysdept));
    }

    /**
     * 添加
     *
     * @param sysDept
     *            实体
     * @return success/false
     */
    @SysLog("添加部门")
    @PostMapping
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('sys_dept_add')")
    public R save(SysDept sysDept) {
        if (sysDept.getParentId() == null)
            sysDept.setParentId(0);
        // 部门编码判重
        List<SysDept> deptlist = sysDeptService.list(Wrappers.<SysDept>query().lambda()
            .eq(SysDept::getDeptCode, sysDept.getDeptCode()).eq(SysDept::getDelFlag, Constants.STATUS_NORMAL));

        if (CollectionUtils.isNotEmpty(deptlist)) {
            return R.failed("部门编码不能重复");
        }
        return R.ok(sysDeptService.saveDept(sysDept));
    }

    /**
     * 删除
     *
     * @param id
     *            ID
     * @return success/false
     */
    @SysLog("删除部门")
    @ResponseBody
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('sys_dept_del')")
    public R removeById(@PathVariable Integer id) {
        // 部门有子部门不能删除
        List<SysDept> deptlist = sysDeptService.list(Wrappers.<SysDept>query().lambda().eq(SysDept::getParentId, id)
            .eq(SysDept::getDelFlag, Constants.STATUS_NORMAL));

        if (CollectionUtils.isNotEmpty(deptlist)) {
            return R.failed("该部门已有子部门，不能删除");
        }
        // 部门已有用户不能删除
        List<SysUser> userlist = userService.list(Wrappers.<SysUser>query().lambda().eq(SysUser::getDeptId, id)
            .eq(SysUser::getDelFlag, Constants.STATUS_NORMAL));

        if (CollectionUtils.isNotEmpty(userlist)) {
            return R.failed("部门已分配用户，不能删除");
        }
        return R.ok(sysDeptService.removeDeptById(id));
    }

    /**
     * 编辑
     *
     * @param sysDept
     *            实体
     * @return success/false
     */
    @SysLog("编辑部门")
    @PutMapping
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('sys_dept_edit')")
    public R update(SysDept sysDept) {
        // 部门编码判重
        List<SysDept> deptlist =
            sysDeptService.list(Wrappers.<SysDept>query().lambda().eq(SysDept::getDeptCode, sysDept.getDeptCode())
                .eq(SysDept::getDelFlag, Constants.STATUS_NORMAL).ne(SysDept::getDeptId, sysDept.getDeptId()));

        if (CollectionUtils.isNotEmpty(deptlist)) {
            return R.failed("部门编码不能重复");
        }
        sysDept.setUpdateTime(new Date());
        return R.ok(sysDeptService.updateDeptById(sysDept));
    }
}
